package front

import (
	"github.com/juju/errors"
	"qihuang/config"
	"qihuang/db/mysql"
	"qihuang/db/redis"
	"qihuang/loger"
	"qihuang/model"
	"qihuang/protocol"
	"strconv"
	"time"
)

type FamilyParams struct {
	Id         int    `json:"id",gorm:"primary_key;AUTO_INCREMENT"`
	CreateTime string `json:"create_time"`
	ModifyTime string `json:"modify_time"`
	Status     int    `json:"status"`
	Deleted    int    `json:"deleted"`
	Relation   string `json:"relation"`
	Birthday   string `json:"birthday"`
	Gender     string `json:"gender"`
	Address    string `json:"address"`
	Job        string `json:"job"`
	Height     string `json:"height "`
	Weight     string `json:"weight"`
	TasteOne   int    `json:"taste_one"`
	Taste      string `json:"taste"`
	Smoke      int    `json:"smoke"`
	Wine       int    `json:"wine"`
	Sleep      int    `json:"sleep"`
	FamilyId   int    `json:"family_id"`
	Diseases   string `json:"diseases"`
}

type Detail struct {
	Id       int    `json:"id",gorm:"primary_key;AUTO_INCREMENT"`
	Relation string `json:"relation"`
	Birthday string `json:"birthday"`
	Gender   string `json:"gender"`
	Address  string `json:"address"`
	Job      string `json:"job"`
	Height   string `json:"height "`
	Weight   string `json:"weight"`
	TasteOne int    `json:"taste_one"`
	Taste    string `json:"taste"`
	Smoke    int    `json:"smoke"`
	Wine     int    `json:"wine"`
	Sleep    int    `json:"sleep"`
	Diseases string `json:"diseases"`
}

type Families struct {
}

type FamilyList struct {
	Total    int            `json:"total"`
	Datalist []model.Family `json:"datalist"`
}

//添加家庭成员
func (c *Families) Add(params *FamilyParams) (resp *protocol.Resp) {
	resp = &protocol.Resp{Status: 1, Msg: "创建失败", Data: ""}
	family := model.Family{
		Deleted:    0,
		Relation:   params.Relation,
		Birthday:   params.Birthday,
		Gender:     params.Gender,
		Address:    params.Address,
		Job:        params.Job,
		Height:     params.Height,
		Weight:     params.Weight,
		TasteOne:   params.TasteOne,
		Taste:      params.Taste,
		Smoke:      params.Smoke,
		Wine:       params.Wine,
		Sleep:      params.Sleep,
		FamilyId:   params.FamilyId,
		Diseases:   params.Diseases,
		ModifyTime: time.Now().Format("2006-01-02 15:04:05"),
		Status:     params.Status,
		CreateTime: time.Now().Format("2006-01-02 15:04:05"),
	}

	db := mysql.Default().GetConn()
	defer db.Close()
	// 开始事务
	tx := db.Begin()
	//添加family
	err := db.Model(model.Family{}).Create(&family).Error
	if err != nil {
		loger.Loger.Error(errors.ErrorStack(errors.Trace(err)))
		resp.Msg = "系统错误"
		tx.Rollback()
		return resp
	}
	//提交事务
	tx.Commit()
	resp.Status = 0
	resp.Msg = "创建成功"
	return resp
}

//更新成员信息
func (c *Families) Update(id int, params *FamilyParams) (resp *protocol.Resp) {
	resp = &protocol.Resp{Status: 1, Msg: "更新失败", Data: ""}
	if err := c.deleteFamilyCache(id); err != nil {
		resp.Msg = "更新失败，请重试！"
		return resp
	}
	//查询ID是否存在
	db := mysql.Default().GetConn()
	defer db.Close()
	count := 0
	if err := db.Model(model.Family{}).Where("id = ?", id).Count(&count).Error; err != nil {
		loger.Loger.Error(errors.ErrorStack(errors.Trace(err)))
		resp.Msg = "系统错误"
		return resp
	}

	if count <= 0 {
		resp.Msg = "家庭成员不存在"
		return resp
	}
	articles := model.Family{
		Relation:   params.Relation,
		Birthday:   params.Birthday,
		Gender:     params.Gender,
		Address:    params.Address,
		Job:        params.Job,
		Height:     params.Height,
		Weight:     params.Weight,
		TasteOne:   params.TasteOne,
		Taste:      params.Taste,
		Smoke:      params.Smoke,
		Wine:       params.Wine,
		Sleep:      params.Sleep,
		FamilyId:   params.FamilyId,
		Diseases:   params.Diseases,
		ModifyTime: time.Now().Format("2006-01-02 15:04:05"),
		Status:     params.Status,
	}

	// 开始事务
	tx := db.Begin()
	//添加articles
	err := db.Model(model.Family{}).Where("id = ?", id).Update(&articles).Error
	if err != nil {
		loger.Loger.Error(errors.ErrorStack(errors.Trace(err)))
		resp.Msg = "系统错误"
		tx.Rollback()
		return resp
	}
	//提交事务
	tx.Commit()
	resp.Status = 0
	resp.Msg = "更新成功"
	return resp
}

//分页获取家庭成员列表
func (c *Families) GetList(familyId int, page int, pageSize int, fields []string) (resp *protocol.Resp) {
	resp = &protocol.Resp{Status: 1, Msg: "获取列表信息失败", Data: ""}
	db := mysql.Default().GetConn()
	defer db.Close()
	offset := (page - 1) * pageSize
	familyList := &FamilyList{}
	families := make([]model.Family, 0)
	total := 0

	db.Model(&model.Family{}).Count(&total)
	if err := db.Where("family_id=?", familyId).Offset(offset).Limit(pageSize).Order("id desc").Find(&families).Error; err != nil {
		loger.Loger.Error(errors.ErrorStack(errors.Trace(err)))
		resp.Msg = "系统错误"
		return resp
	}
	familyList.Datalist = families
	familyList.Total = total
	resp.Status = 0
	resp.Msg = "获取列表成功"
	resp.Data = familyList
	return resp
}

//分页获取家庭成员列表
func (c *Families) GetFamilyList(familyId int, page int, pageSize int) (familyList []model.Family) {
	db := mysql.Default().GetConn()
	defer db.Close()
	offset := (page - 1) * pageSize
	families := make([]model.Family, 0)
	total := 0

	db.Model(&model.Family{}).Count(&total)
	if err := db.Where("family_id=?", familyId).Offset(offset).Limit(pageSize).Order("id desc").Find(&families).Error; err != nil {
		return families
	}
	return families
}

//删除文章
func (c *Families) Delete(id int) (resp *protocol.Resp) {
	resp = &protocol.Resp{Status: 1, Msg: "删除失败", Data: ""}
	db := mysql.Default().GetConn()
	defer db.Close()
	if err := c.deleteFamilyCache(id); err != nil {
		resp.Msg = "删除失败，请重试！"
		return resp
	}
	if err := db.Where("id = ?", id).Delete(&model.Family{}).Error; err != nil {
		loger.Loger.Error(errors.ErrorStack(errors.Trace(err)))
		resp.Msg = "系统错误"
		return resp
	}
	resp.Status = 0
	resp.Msg = "删除成功！"
	return resp
}

//文章详情
func (c *Families) GetDetail(id int) (resp *protocol.Resp) {
	resp = &protocol.Resp{Status: 1, Msg: "", Data: ""}
	db := mysql.Default().GetConn()
	defer db.Close()
	article := &model.Family{}
	//article_content := &model.ArticlesContents{}

	if err := db.Where("id = ?", id).Find(article).Error; err != nil {
		loger.Loger.Error(errors.ErrorStack(errors.Trace(err)))
		resp.Msg = "系统错误"
		return resp
	}
	detail := &Detail{}
	detail.Relation = article.Relation
	detail.Id = id
	detail.Birthday = article.Birthday
	detail.Gender = article.Gender
	detail.Address = article.Address
	detail.Job = article.Job
	detail.Weight = article.Weight
	detail.TasteOne = article.TasteOne
	detail.Height = article.Height
	detail.Taste = article.Taste
	detail.Smoke = article.Smoke
	detail.Wine = article.Wine
	detail.Diseases = article.Diseases
	detail.Sleep = article.Sleep
	resp.Data = detail
	resp.Status = 0
	return resp
}

func (c *Families) deleteFamilyCache(id int) error {
	redisConn := redis.RedisClient.Pool.Get()
	cacheKey := "family_" + config.Configs.RedisCacheVersion + ":" + strconv.Itoa(id)
	if err := redisConn.Err(); err != nil {
		loger.Loger.Error(errors.ErrorStack(errors.Trace(err)))
		return err
	}
	_, err := redisConn.Do("del", cacheKey)
	if err != nil {
		loger.Loger.Error(errors.ErrorStack(errors.Trace(err)))
		return err
	}
	return nil
}
